<template>
  <div style="position: absolute; top: 1px; left: 100px">
    <n-button type="success" style="margin-bottom: 12px" @click="handleClick"> 上传文件 </n-button>
  </div>
  <div>
    <n-upload
      ref="uploadRef"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :data="{ folder: 'information' }"
      :default-upload="false"
      name="files"
      multiple
      v-model:file-list="fileList"
      @change="handleChange"
      @finish="handleFinish"
    >
      <n-button>选择文件</n-button>
    </n-upload>
  </div>
</template>

<script lang="ts" setup>
  import { useGlobSetting } from '@/hooks/setting';
  import type { UploadFileInfo, UploadInst } from 'naive-ui';
  import { reactive, ref, watch } from 'vue';
  import { useUser } from '@/store/modules/user';
  import componentSetting from '@/settings/componentSetting';
  import { ResultEnum } from '@/enums/httpEnum';

  const fileId = ref<any>([]);
  const fileList = ref<any>([]);
  const uploadRef = ref<UploadInst | null>(null);
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadHeaders = reactive({
    platform: 'miniPrograms',
    timestamp: new Date().getTime(),
    Authorization: 'Bearer ' + useUser().getToken,
  });

  const props = defineProps<{
    data: any;
  }>();

  watch(
    () => props,
    () => {
      fileList.value = props.data;
    },
    { immediate: true }
  );

  const emit = defineEmits(['uploadFileChange']);
  const handleChange = (options: { fileList: UploadFileInfo[] }) => {
    console.log(options);
  };

  // const handleFinish = (files:any, event:any) => {
  //   console.log(event)
  //   // emit('uploadFileChange', options.fileList);
  // };

  const handleFinish = ({ event: Event }) => {
    const res = eval('(' + Event.target.response + ')');
    const infoField = componentSetting.upload.apiSetting.infoField;
    const { code } = res;
    const message = res.msg || res.message || '上传失败';
    const result = res[infoField];
    //成功
    if (code === ResultEnum.SUCCESS) {
      fileId.value.push(result.id);
      emit('uploadFileChange', fileId.value.join(','));
    } else message.error(message);
  };

  const handleClick = () => {
    uploadRef.value?.submit();
  };
</script>
